package com.sdh.onlinemarket.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdh.onlinemarket.common.annotation.AdminToken;
import com.sdh.onlinemarket.common.annotation.UserLoginToken;
import com.sdh.onlinemarket.common.lang.Result;
import com.sdh.onlinemarket.common.util.TokenService;
import com.sdh.onlinemarket.common.util.TokenUtil;
import com.sdh.onlinemarket.entity.Usersecure;
import com.sdh.onlinemarket.service.UsersecureService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 施德昊
 * @since 2022-01-10
 */
@Api(tags = "登录相关模块")
@RestController
@RequestMapping("/usersecure")
public class UsersecureController {

    @Autowired
    UsersecureService usersecureService;
    @Autowired
    TokenService tokenService;

    // 登录
    @ApiOperation(value = "登陆", notes = "登陆")
    @RequestMapping(value = "/login" ,method = RequestMethod.GET)
    public Result login(Usersecure usersecure, HttpServletResponse response) {
        Usersecure userForBase = usersecureService.getOne(new QueryWrapper<Usersecure>().eq("account",usersecure.getAccount()));
//        userForBase.setAccount(userService.findByUsername(user).getId());
//        userForBase.setUsername(userService.findByUsername(user).getUsername());
//        userForBase.setPassword(userService.findByUsername(user).getPassword());
        if(userForBase == null){
            return Result.fail("参数错误"+usersecure.toString());
        }
        if (!userForBase.getPassword().equals(usersecure.getPassword())) {
            return Result.fail("密码错误，登录失败") ;
        } else {
            String token = tokenService.getToken(userForBase);
            Cookie cookie = new Cookie("token", token);
            cookie.setPath("/");
            response.addCookie(cookie);
            return Result.succ(token);
        }
    }
    /***
     * 这个请求需要验证token才能访问
     */
    @UserLoginToken
    @ApiOperation(value = "获取信息", notes = "测试验证TOKEN")
    @GetMapping("/getmessage")
    public String getMessage() {
        // 取出token中带的用户id 进行操作
        System.out.println(LocalDateTime.now()+"--------"+TokenUtil.getTokenUserId());
        return "您已通过验证";
    }
}
